//
//  RWOrderListViewController.m
//  RedWine
//
//  Created by Liufangfang on 2016/12/27.
//  Copyright © 2016年 HuiBangKe. All rights reserved.
//

#import "RWOrderListViewController.h"
#import "RWOrderListTableViewCell.h"
#import "RWOrderDetailViewController.h"
#import "RWBalancePayViewController.h"
#import "AppDelegate.h"

#import "RWMyOrderModel.h"
#import "UIViewController+BackButtonHandler.h"

@interface RWOrderListViewController ()<RWOrderListTableViewCellDelegate>{

    NSString *currentOrderSn;
}

@property (nonatomic, copy) NSMutableArray *myOrderModels;

@end

@implementation RWOrderListViewController

#pragma mark - View LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initObjects];
    [self loadDatas];
    [self setNavigation];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Load Datas

- (void)initObjects{
    
    _myOrderModels = [NSMutableArray array];
}

- (void)loadDatas{

    FTYUser *user = [FTYUser sharedUser];
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=orderlist&member_id=%@&token=%@&state=%@", user.userID, user.userToken, _orderState] parameters:nil block:^(id result, NSError *error) {
        
        if (!error) {
            
            DLog(@"订单列表====%@", result);
            FTYBaseModel *baseModel = [[FTYBaseModel alloc] init];
            baseModel = [FTYBaseModel mj_objectWithKeyValues:result];
            FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
            
            if (0 == errorInfo.errorcode) {
            
                [_myOrderModels addObjectsFromArray:baseModel.info];
                
                [self setOrderListUI];
            } else {
                [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
            }
        } else {
        
        }
    }];
}

#pragma mark - Config UI

- (void)setNavigation{
    
    self.title = _tableTitle;
/*    //自定义返回按钮
    self.navigationItem.hidesBackButton  = YES;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"return_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(backToMineTab:)];
 */
   
}

- (void)setOrderListUI{
    
    _orderListTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, FTY_SCREEN_HEIGHT - FTY_STATUS_HEIGHT - FTY_NAVIGATION_HEIGHT) style:UITableViewStylePlain];
    _orderListTV.backgroundColor = [FTYColor whiteColor];
    [self.view addSubview:_orderListTV];
    _orderListTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _orderListTV.dataSource = self;
    _orderListTV.delegate = self;
}

#pragma mark - Config Invoke Methods
/*
- (void)backToMineTab:(id)sender
{
    //进入个人中心
    [sharedDelegate showWindowHome:@"my"];
}
*/

- (BOOL)navigationShouldPopOnBackButton
{
    //进入个人中心
    [sharedDelegate showWindowHome:@"my"];
    return NO;
}
#pragma mark - Notificaiton Method

#pragma mark - Notificaiton Invoke Methods

#pragma mark - <UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _myOrderModels.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 250.*FTY_HEIGHT_BASE;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString * const orderListID = @"orderListID";
    RWOrderListTableViewCell *orderListCell = [tableView dequeueReusableCellWithIdentifier:orderListID];
    
    if (!orderListCell) {
    
        orderListCell = [[RWOrderListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:orderListID];
        orderListCell.selectionStyle = UITableViewCellSeparatorStyleNone;
        orderListCell.delegate = self;
    }
    [orderListCell loadDataWithModel:_myOrderModels[indexPath.row]];
    
    return orderListCell;
}

#pragma mark - <UITableViewDelegate>

#pragma mark - <RWOrderListTableViewCellDelegate>

- (void)orderListAction:(UIButton *)btn orderSN:(NSString *)orderSn{

    currentOrderSn = orderSn;
    switch (btn.tag) {
        case 580:
            //订单详情
            [self orderDetail];
            break;
        case 581:
            //取消订单
            [self cancelOrder];
            break;
        case 582:
            //去付款
            [self toPay];
            break;
        case 583:
            //确认收货
            [self sureRecieve];
            break;
        default:
            break;
    }
}

#pragma mark - Private Invoke Methods

- (void)orderDetail{

    RWOrderDetailViewController *orderDetailV = [[RWOrderDetailViewController alloc] init];
    orderDetailV.orderSN = currentOrderSn;
    [self.navigationController pushViewController:orderDetailV animated:YES];
}

- (void)cancelOrder{

    FTYUser *user = [FTYUser sharedUser];
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=cancelorder&member_id=%@&token=%@&order_sn=%@", user.userID, user.userToken, currentOrderSn] parameters:nil block:^(id result, NSError *error) {
        
        if (!error) {
            
            DLog(@"取消订单====%@", result);
            FTYBaseModel *baseModel = [[FTYBaseModel alloc] init];
            baseModel = [FTYBaseModel mj_objectWithKeyValues:result];
            FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
            
            if (0 == errorInfo.errorcode) {
                [[FTYToastView alloc] addTitle:@"取消订单成功～" addView:self.view];
                NSArray *tempArr = [NSArray arrayWithArray:_myOrderModels];
                for (NSDictionary *orderDict in tempArr) {
                    ;
                    NSString *orderSn = [orderDict objectForKey:@"order_sn"];
                    if ([orderSn isEqualToString:currentOrderSn]) {
                        [_myOrderModels removeObject:orderDict];
                    }
                }
                [self.orderListTV reloadData];
            } else {
                [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
            }
        } else {
            
        }
    }];
}

- (void)toPay{

    RWBalancePayViewController *balancePayV = [[RWBalancePayViewController alloc] init];
    balancePayV.orderSN = currentOrderSn;
    [self.navigationController pushViewController:balancePayV animated:YES];
}

- (void)sureRecieve
{
    FTYUser *user = [FTYUser sharedUser];
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=received&member_id=%@&token=%@&order_sn=%@", user.userID, user.userToken, currentOrderSn] parameters:nil block:^(id result, NSError *error) {
        
        if (!error) {
            
            DLog(@"确认收货====%@", result);
            FTYBaseModel *baseModel = [[FTYBaseModel alloc] init];
            baseModel = [FTYBaseModel mj_objectWithKeyValues:result];
            FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
            
            if (0 == errorInfo.errorcode) {
                [[FTYToastView alloc] addTitle:@"确认收货成功～" addView:self.view];
                NSArray *tempArr = [NSArray arrayWithArray:_myOrderModels];
                for (NSDictionary *orderDict in tempArr) {
                    ;
                    NSString *orderSn = [orderDict objectForKey:@"order_sn"];
                    if ([orderSn isEqualToString:currentOrderSn]) {
                        [_myOrderModels removeObject:orderDict];
                    }
                }
                [self.orderListTV reloadData];
            } else {
                [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
            }
        } else {
            
        }
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
